//
//  StatusItemPopup.m
//  StatusItemPopup
//
//  Created by Alexander Schuch on 06/03/13.
//  Copyright (c) 2013 Alexander Schuch. All rights reserved.
//

#import "ZTPopup.h"

#define kMinViewWidth 22

//
// Private variables
//
@interface ZTPopup () {
    NSViewController *_viewController;
    id _popoverTransiencyMonitor;
}

@property(nonatomic, strong, readwrite) NSPopover* popover;

@end

///////////////////////////////////

//
// Implementation
//
@implementation ZTPopup


- (id)initWithViewController:(NSViewController *)controller
{
    CGFloat height = [NSStatusBar systemStatusBar].thickness;
    
    self = [super initWithFrame:NSMakeRect(0, 0, kMinViewWidth, height)];
    if (self) {
        _viewController = controller;
        _animated = YES;
    }
    return self;
}


////////////////////////////////////
#pragma mark - Drawing
////////////////////////////////////

- (void)drawRect:(NSRect)dirtyRect
{
    // set view background color
}

////////////////////////////////////
#pragma mark - Position / Size
////////////////////////////////////

- (void)setContentSize:(CGSize)size
{
    _popover.contentSize = size;
}


////////////////////////////////////
#pragma mark - Show / Hide Popover
////////////////////////////////////

- (void)showPopover:(id)sender
{
    if (!_popover) {
        _popover = [[NSPopover alloc] init];
        _popover.contentViewController = _viewController;
        _popover.animates =_animated;
        
    }
    if (!_popover.isShown) {
        _popover.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
        NSButton* btn = sender;
        NSRect cellRect = [btn bounds];
        [_popover showRelativeToRect:cellRect ofView:btn preferredEdge:NSMaxXEdge];
    }
}


- (void)hidePopover
{
    if (_popover && _popover.isShown) {
        [_popover close];

		if (_popoverTransiencyMonitor) {
            [NSEvent removeMonitor:_popoverTransiencyMonitor];
            _popoverTransiencyMonitor = nil;
        }
    }
}

@end

